package com.example.njupt.okhttp.retrofit;

import androidx.fragment.app.Fragment;

import com.example.njupt.constant.ApiConstance;
import com.example.njupt.okhttp.RetrofitInterceptor;
import com.example.njupt.service.ApiService;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Author:      mwang
 * Create Date: Created in 2021/4/26 14:25
 * Update Date:
 * Modified By:
 * Description: retrofit
 */
public class ApiRetrofit {
    private static ApiRetrofit apiRetrofit;
    private Retrofit retrofit;
    private OkHttpClient client;
    private ApiService apiService;

    public static String CURRENT_PAGE_NAME = "";
    public static String CURRENT_PAGE_TYPE = "";

    private static class ApiRetrofitHelper{
        private static ApiRetrofit instance = new ApiRetrofit();
    }
    public ApiRetrofit() {
        client = new OkHttpClient.Builder()
                .addInterceptor(new RetrofitInterceptor()) //添加日志拦截
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .build();

        retrofit = new Retrofit.Builder()
                .baseUrl(ApiConstance.URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(client)
                .build();
        if (apiService == null) {
            apiService = retrofit.create(ApiService.class);
        }
    }

    public static ApiRetrofit getInstance(Object object) {
        if (null != object){
            CURRENT_PAGE_NAME = object.getClass().getSimpleName();
            if ("WebActivity".equals(CURRENT_PAGE_NAME)){
                CURRENT_PAGE_TYPE = "web";
            }else if (object instanceof Fragment){
                CURRENT_PAGE_TYPE = "fragment";
            }else {
                CURRENT_PAGE_TYPE = "activity";
            }
        }
        return ApiRetrofitHelper.instance;
    }

    public ApiService getApiService() {
        return apiService;
    }
}
